import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';

import '../../AppConfig/LocalStorage.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/api.dart';

class NoInvoicingSpecified extends StatefulWidget {
  const NoInvoicingSpecified({super.key, required this.carMap, required this.goodsMap});
  final Map carMap;
  final Map goodsMap;

  @override
  State<NoInvoicingSpecified> createState() => _NoInvoicingSpecifiedState();
}

class _NoInvoicingSpecifiedState extends State<NoInvoicingSpecified> {
  String deposit="";
  String freight="";
  int freightType=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.goodsMap['freight']!=0)
      freight =widget.goodsMap['freight'].toString();
    if(widget.goodsMap['deposit']!=0)
      deposit =widget.goodsMap['deposit'].toString();
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "指定承运",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Column(
        children: [
          Expanded(child: ListView(children: [
            Container(
              margin: EdgeInsets.only(top: 8.h,left: 26.w),
              child:Row(
                children: [
                  Text("您指定的司机",style: TextStyle(color: MyColors.authTipColor),),
                  Text(widget.carMap['realName']+"("+widget.carMap['vehicleLength'].toString()+"/"+widget.carMap['vehicleModel'].toString()+")",style: TextStyle(color: Colors.black),),
                  Text("承运",style: TextStyle(color: MyColors.authTipColor),),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 10.h,bottom: 10.h),
              margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              child: Column(
                children: [

                  Row(
                    children: [
                      Container( constraints: BoxConstraints(
                        maxWidth:(screenSize.width-90.w)/2, // 限制文本最大宽度
                      ),child: Text(widget.goodsMap['loadPlaceInfo'][0]['city']+" "+ widget.goodsMap['loadPlaceInfo'][0]['county'],overflow:TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 14.sp),),),

                       Image.asset("lib/Images/PersonCenter/我的评价箭头.png",width:20.w ,height: 20.h,),
                      Container(constraints: BoxConstraints(
                    maxWidth:(screenSize.width-60.w)/2, // 限制文本最大宽度
                    ),child: Text(widget.goodsMap['unloadPlaceInfo'][0]['city']+" "+ widget.goodsMap['unloadPlaceInfo'][0]['county'],overflow:TextOverflow.ellipsis ,style: TextStyle(color: Colors.black,fontSize: 14.sp),),),

                    ],
                  ),
                  SizedBox(height:11.h ,),
                  Row(
                    children: [
                      Icon(Icons.notifications_none,color: MyColors.textColor,),
                      SizedBox(width: 4.w,),
                      Text("需求"+widget.goodsMap['vehicleLength'].toString()+"米/"+widget.goodsMap['vehicleModel'].toString(),style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                    ],
                  ),
                  SizedBox(height: 20.h,),
                  Container(
                    padding: EdgeInsets.only(left: 11.w,right: 11.w),
                    height: 42.h,
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(239, 239, 239, 1),
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("运费",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        Row(
                          children: [
                            Container(
                              width: 150.w,
                              height: 35.h,
                              child:  TextField(
                                decoration: InputDecoration(
                                  hintText:widget.goodsMap['freight']!=0?widget.goodsMap['freight'].toString(): '必填，50-50000',
                                  // labelText:widget.editType==1?"":depositNum ,
                                  hintStyle:TextStyle(fontSize: 14.sp,color:widget.goodsMap['freight']!=0?Colors.black: MyColors.hintColor),
                                  filled: true,
                                  fillColor:Color.fromRGBO(239, 239, 239, 1),
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  // contentPadding: EdgeInsets.symmetric(vertical:9.5.h, horizontal: 0.0.w),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.right,
                                style: TextStyle(color: Colors.black),
                                onChanged: (value) {
                                  setState(() {
                                   freight=value;
                                  });
                                },
                              ),
                            ),
                                SizedBox(width: 6.w,),
                            Text("元",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        )
                      ],
                    ),
                  ),
                SizedBox(height: 14.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [


                      if(freightType==1)
                        Text("¥" + freight, style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                      if(freightType==3)
                        Text("总运费："+(double.parse(freight)*widget.goodsMap['cargoInfo'][0]['cargoWeight']).toStringAsFixed(2)+"元",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      if(freightType==2)
                        Text("总运费："+(double.parse(freight)*widget.goodsMap['cargoInfo'][0]['cargoVolume']).toStringAsFixed(2)+"元",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      Row(
                        children: [
                          BrnSmallMainButton(
                            title: '趟',
                            width: 40.w,
                            fontSize: 14.sp,
                            bgColor: freightType==1?Color.fromRGBO(251, 236, 228, 1):MyColors.backgreyColor,
                            textColor: freightType==1?MyColors.themeColor:Colors.black,
                            fontWeight: FontWeight.w100,
                            onTap: () {
                              setState(() {
                                freightType=1;
                              });
                            },
                          ),
                          SizedBox(width: 4.w,),
                          if(widget.goodsMap['cargoInfo'][0]['cargoWeight']!=null)
                            BrnSmallMainButton(
                              title: '吨',
                              width: 40.w,
                              fontSize: 14.sp,
                              bgColor: freightType==3?Color.fromRGBO(251, 236, 228, 1):MyColors.backgreyColor,
                              textColor: freightType==3?MyColors.themeColor:Colors.black,
                              fontWeight: FontWeight.w100,
                              onTap: () {
                                setState(() {
                                  freightType=3;
                                });
                              },
                            ),
                          SizedBox(width: 4.w,),
                          if(widget.goodsMap['cargoInfo'][0]['cargoVolume']!=null)
                            BrnSmallMainButton(
                              title: '方',
                              width: 40.w,
                              bgColor: freightType==2?Color.fromRGBO(251, 236, 228, 1):MyColors.backgreyColor,
                              fontSize: 14.sp,
                              textColor: freightType==2?MyColors.themeColor:Colors.black,
                              fontWeight: FontWeight.w100,
                              onTap: () {
                                setState(() {
                                  freightType=2;
                                });
                              },
                            )
                        ],
                      )
                    ],
                  ),
                  SizedBox(height: 14.h,),
                  Container(
                    padding: EdgeInsets.only(left: 11.w,right: 11.w),
                    height: 42.h,
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(239, 239, 239, 1),
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text("订金",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                            Text(widget.goodsMap['depositType']==0?"（退还）":"（不退还）",style:TextStyle(color:Color.fromRGBO(102, 102, 102, 1),fontSize: 12.sp),),
                          ],
                        ),
                       
                        Row(
                          children: [
                            Container(
                              width: 150.w,
                              height: 35.h,
                              child:  TextField(
                                decoration: InputDecoration(
                                  hintText:widget.goodsMap['deposit']!=0?widget.goodsMap['deposit'].toString(): '选填，20-500',
                                  // labelText:widget.editType==1?"":depositNum ,
                                  hintStyle:TextStyle(fontSize: 14.sp,color:widget.goodsMap['deposit']!=0?Colors.black:  MyColors.hintColor),
                                  filled: true,
                                  fillColor:Color.fromRGBO(239, 239, 239, 1),
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  // contentPadding: EdgeInsets.symmetric(vertical: 9.5.h, horizontal: 0.0.w),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.right,
                                style: TextStyle(color: Colors.black),
                                onChanged: (value) {
                                  setState(() {
                                    deposit=value;
                                  });
                                },
                              ),
                            ),
                            SizedBox(width: 6.w,),
                            Text("元",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 12.h,),
                  Row(
                    children: [
                      Icon(Icons.error_outline,color: MyColors.themeColor,size: 12,),
                      Text("司机支付订金到平台用于订货押金，您收到货后，退还给司机",style: TextStyle(color: MyColors.themeColor,fontSize: 10.sp),),
                    ],
                  )
                ],
              ),
            ),
          ],
          ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            width: screenSize.width,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 10.h,bottom: 40.h),
            child: BrnSmallMainButton(
              title: '提交',
              bgColor: MyColors.themeColor,
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              radius: 30,
              onTap: () async {
                // if (freight.contains(".")) {
                //   // 如果字符串中包含点
                //   List<String> parts = freight.split(".");
                //   // 拆分字符串
                //
                //   if (parts[1].length == 2) {
                //     // 如果点后面有两位
                //     freight = freight.replaceAll(".", "");
                //   } else if (parts[1].length == 1) {
                //     // 如果点后面有一位
                //     freight = freight.replaceAll(".", "") + "0";
                //   }
                // }else{
                //   freight=(int.parse(freight)*100).toString();
                // }
                // if (deposit.contains(".")) {
                //   // 如果字符串中包含点
                //   List<String> parts = deposit.split(".");
                //   // 拆分字符串
                //
                //   if (parts[1].length == 2) {
                //     // 如果点后面有两位
                //     deposit = deposit.replaceAll(".", "");
                //   } else if (parts[1].length == 1) {
                //     // 如果点后面有一位
                //     deposit = deposit.replaceAll(".", "") + "0";
                //   }
                // }else{
                //   deposit=(int.parse(deposit)*100).toString();
                // }

                LoadingDialog.show(context);
                String? shipperId = await UserIdManager.getUserID();
                String? token = await TokenManager.getToken();
                dio.interceptors.add(InterceptorsWrapper(
                    onRequest: (options, handler) {
                      options.headers["satoken"] = token;
                      return handler.next(options);
                    }
                ));
                dio.post(
                  MyServiceUrl.header+'api/waybill/waybill/shipper/dispatchWaybill',
                  data: {
                    "sourceId": widget.goodsMap['id'],
                    "drvId": widget.carMap['drvId']==null?widget.carMap['driverId']:widget.carMap['drvId'],
                    "shipperId": shipperId,
                    "companyId": "",
                    "priceUnit":freightType,
                    "deposit":deposit,
                    "freight":freight
                  },
                  options: Options(
                    sendTimeout: Duration(seconds: 2),
                    receiveTimeout: Duration(seconds: 50),
                  ),
                  onSendProgress: (a, b) => print('send ${a / b}'),
                  onReceiveProgress: (a, b) =>
                      print('received ${a / b}'),
                )
                    .then((r) {
                  setState(() {
                    print(r);
                    Map<String, dynamic> jsonMap = json.decode(
                        r.toString());
                    // 获取code和data
                    String code = jsonMap['code'].toString();
                    if (code == "200") {
                      LoadingDialog.hide(context);
                      BrnToast.show("提交成功", context);

                      Navigator.pushAndRemoveUntil(
                        context,
                        MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,)), // 推入第二个页面
                            (route) => false, // 从栈中移除所有页面，包括当前页面和第一个页面
                      );
                    }else{
                      LoadingDialog.hide(context);
                      BrnToast.show(jsonMap['msg'], context);
                    }
                  });
                }).catchError((error) {
                  print(error);
                  ;
                });
              },
            ),
          )

        ],
      ),
    );

  }
}
